package com.somewater.game.controllers
{
	import com.somewater.storage.InfoDef;
	import com.somewater.storage.Lib;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	/**
	 * Прорисовка игровых объектов
	 */
	public class Render extends Component
	{
		
		public var displayObject:DisplayObject;
		
		private var spatialRef:Spatial;
		
		public function Render(owner:Entity)
		{
			super(owner);
		}
		
		
		override public function clear():void
		{
			super.clear();
			if(displayObject)
				clearDisplayObject();
		}
		
		
		/**
		 * Обновить положение объекта согласно данным их Spatial
		 */
		public function onTick(deltaTime:Number):void
		{
			if(displayObject == null)
				recreateDisplayObject();
			
			if(spatialRef == null)
				spatialRef = owner.spatial;
			
			displayObject.x = spatialRef.x;
			displayObject.y = -spatialRef.y;
		}
		
		
		private function recreateDisplayObject():void
		{
			if(displayObject)
				clearDisplayObject();
			displayObject = Lib.getMc("Hero" + owner.user.avatarIndex);
			
			if(displayObject is MovieClip)
			{
				MovieClip(displayObject).gotoAndPlay(int(MovieClip(displayObject).totalFrames * Math.random()));
			}
			
			displayObject.addEventListener(MouseEvent.ROLL_OVER, onDORollOver);
			displayObject.addEventListener(MouseEvent.ROLL_OUT, onDORollOut);
			
			SpatialController.instance.entityLayerRef.addChild(displayObject);			
		}
		
		
		private function clearDisplayObject():void
		{
			displayObject.removeEventListener(MouseEvent.ROLL_OVER, onDORollOver);
			displayObject.removeEventListener(MouseEvent.ROLL_OUT, onDORollOut);
			if(displayObject.parent)
				displayObject.parent.removeChild(displayObject);
			displayObject = null;
		}
		
		
		private function onDORollOver(e:MouseEvent):void
		{
			owner.dispatchEvent(new Event(Entity.ENTITY_ROLL_OVER));
		}
		
		
		private function onDORollOut(e:MouseEvent):void
		{
			owner.dispatchEvent(new Event(Entity.ENTITY_ROLL_OUT));
		}
	}
}